package com.ktjiaoyu.web.filter;

import com.ktjiaoyu.pojo.SysUser;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class AuthorizationFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.从session中获取登录用户信息
        HttpServletRequest request= (HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;

        HttpSession session = request.getSession();
        SysUser loginUser = (SysUser)session.getAttribute("loginUser");
        //1.1 获取到了 有登录
        if(loginUser!=null){
            //放行
            filterChain.doFilter(request,response);
        }else{//1.2 没有获取到 没有登录
            response.setContentType("text/html; charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print("<script>alert('请先进行登陆，再进行后续操作！(Filter控制)');location.href='/login.jsp';</script>");
        }

    }
}
